import axios from 'axios'
import { Message } from 'element-ui'
import { getToken,removeToken } from '@/utils/auth'

// create an axios instance
const service = axios.create({
  baseURL: 'http://localhost:8080', // 直接设置后端地址
  timeout: 15000 // 增加超时时间到15秒
})

// request interceptor
service.interceptors.request.use(
  config => {
    //设置token
    config.headers['Authorization'] = getToken()
    
    // 如果是文件上传，不设置Content-Type，让浏览器自动设置
    if (config.data instanceof FormData) {
      delete config.headers['Content-Type']
    }
    
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
  */

  /**
   * Determine the request status by custom status
   * Here is just an example
   * You can also judge the status by HTTP Status status
   */
  response => {
    const res = response.data

    // 判断请求是否成功
    if (!res.flag) {
      Message({
        message: res.message || 'Error',
        type: 'error',
        duration: 5 * 1000
      })

      // token失效
      if (res.code === 20006) {
        removeToken()
        localStorage.removeItem('vuex')
        setTimeout(() => {
          location.href = "/"
        }, 1000);
      }
      return Promise.reject(res.message || 'Error')
    } else {
      return res
    }
  },
  error => {
    console.log('err' + error) // for debug
    Message({
      message: error.message || '请求失败',
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

export default service